﻿#if _MSC_VER >= 1600
#pragma execution_character_set("utf-8")
#endif

#include "serial.h"

Serial::Serial()
{
    objSerial = new QSerialPort(this);
    connect(objSerial,&QSerialPort::readyRead,this,&Serial::SerialRead);
}
Serial::~Serial()
{
    CloseSerial();
    objSerial->deleteLater();
}
void Serial::OpenSerial(const QString PortName,
                        const qint32 BaudRate,
                        const qint8 DataBits,
                        const qint8 StopBits,
                        const qint8 Parity,
                        const qint8 FlowControl)
{
    objSerial->setPortName(PortName);
    if(objSerial->open(QIODevice::ReadWrite))
    {
        objSerial->setBaudRate(BaudRate);
        switch(DataBits)
        {
        case 5:
            objSerial->setDataBits(QSerialPort::Data5); break;
        case 6:
            objSerial->setDataBits(QSerialPort::Data6); break;
        case 7:
            objSerial->setDataBits(QSerialPort::Data7); break;
        default:
            objSerial->setDataBits(QSerialPort::Data8); break;
        }
        switch(StopBits)
        {
        case 1:
            objSerial->setStopBits(QSerialPort::OneAndHalfStop); break;
        case 2:
            objSerial->setStopBits(QSerialPort::TwoStop); break;
        default:
            objSerial->setStopBits(QSerialPort::OneStop); break;
        }
        switch(Parity)
        {
        case 1:
            objSerial->setParity(QSerialPort::EvenParity); break;
        case 2:
            objSerial->setParity(QSerialPort::OddParity); break;
        case 3:
            objSerial->setParity(QSerialPort::SpaceParity); break;
        case 4:
            objSerial->setParity(QSerialPort::MarkParity); break;
        default:
            objSerial->setParity(QSerialPort::NoParity); break;
        }
        switch(FlowControl)
        {
        case 1:
            objSerial->setFlowControl( QSerialPort::HardwareControl); break;   //RTS/CTS
        case 2:
            objSerial->setFlowControl(QSerialPort::SoftwareControl); break;    //XON/XOFF
        default:
            objSerial->setFlowControl(QSerialPort::NoFlowControl); break;
        }
    }
}
void Serial::CloseSerial()
{
    if(objSerial->isOpen())
    {
        //清除串口缓存
        objSerial->clear();
        //关闭串口
        objSerial->close();
    }
}
void Serial::SerialWrite(const QByteArray& data)
{
    objSerial->write(data);
}
void Serial::SerialRead()
{
    emit recive(objSerial->readAll());
}
